#!/bin/bash

# Docker构建脚本
# 用于构建九霄云阙React应用的Docker镜像

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
IMAGE_NAME="novemsite-react"
IMAGE_TAG="latest"
FULL_IMAGE_NAME="${IMAGE_NAME}:${IMAGE_TAG}"

echo -e "${BLUE}🚀 开始构建九霄云阙React应用Docker镜像...${NC}"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}❌ Docker未运行，请先启动Docker${NC}"
    exit 1
fi

# 清理旧的镜像（可选）
read -p "是否清理旧的镜像？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}🧹 清理旧镜像...${NC}"
    docker rmi $FULL_IMAGE_NAME 2>/dev/null || true
fi

# 构建镜像
echo -e "${BLUE}🔨 构建Docker镜像: ${FULL_IMAGE_NAME}${NC}"
docker build -t $FULL_IMAGE_NAME .

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ 镜像构建成功！${NC}"
    
    # 显示镜像信息
    echo -e "${BLUE}📊 镜像信息:${NC}"
    docker images $FULL_IMAGE_NAME
    
    # 询问是否运行容器
    echo
    read -p "是否立即运行容器？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}🏃 启动容器...${NC}"
        docker run -d -p 3000:80 --name novemsite-react-container $FULL_IMAGE_NAME
        echo -e "${GREEN}✅ 容器已启动！访问 http://localhost:3000 查看应用${NC}"
    fi
else
    echo -e "${RED}❌ 镜像构建失败！${NC}"
    exit 1
fi
